package org.kkk.sandbox.sandbox.impl;
import java.io.*;
import java.util.ArrayList;

import lombok.extern.slf4j.Slf4j;
import org.kkk.sandbox.enums.JudgeInfoMessageEnum;
import org.kkk.sandbox.model.*;
import org.kkk.sandbox.utils.ProcessUtils;
@Slf4j
public class JavaNativeCodeSandbox extends CodeSandboxTemplate {

    /**
     *
     * description: 执行方法
     * @param executeCodeRequest
     * @param file
     * @return ExecuteCodeResponse
     * @author  lenovo
     * create 2024/6/2-23:55
     */
    @Override
    protected ExecuteCodeResponse run(ExecuteCodeRequest executeCodeRequest,File file) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        ArrayList<CaseExecuteInfo> caseExecuteInfos = new ArrayList<>();
        //执行代码
            for (String s : executeCodeRequest.getInputList()) {
                //遍历每一个实例
                String command = String.format("java -Dfile.encoding=UTF-8 -cp %s Main", file.getParentFile().getAbsolutePath());
                try {
                    Process codeExecProcess = Runtime.getRuntime().exec(command);
                    ProcessExecuteMessage processExecuteMessage = ProcessUtils.runInteractProcess(codeExecProcess, s, executeCodeRequest.getJudgeConfig());
                    CaseExecuteInfo caseExecuteInfo = new CaseExecuteInfo();
                    if (ProcessUtils.isSuccess(processExecuteMessage.getExitCode())) {
                        //成功
                        caseExecuteInfo.setMemory(processExecuteMessage.getExecMemory());
                        caseExecuteInfo.setTime(processExecuteMessage.getExecTime());
                        caseExecuteInfo.setOutput(processExecuteMessage.getMessage());
                        caseExecuteInfo.setState(JudgeInfoMessageEnum.WAITING.getCode());
                    } else {
                        caseExecuteInfo.setMemory(processExecuteMessage.getExecMemory());
                        caseExecuteInfo.setTime(processExecuteMessage.getExecTime());
                        caseExecuteInfo.setOutput(null);
                        caseExecuteInfo.setState(JudgeInfoMessageEnum.RUNTIME_ERROR.getCode());
                    }
                    caseExecuteInfos.add(caseExecuteInfo);
                } catch (Exception e) {
                    caseExecuteInfos.add(new CaseExecuteInfo(0L,0L,JudgeInfoMessageEnum.SYSTEM_ERROR.getCode(),JudgeInfoMessageEnum.SYSTEM_ERROR.getMessage()));
                }
            }
            executeCodeResponse.setCaseExecuteInfo(caseExecuteInfos);
        return executeCodeResponse;
    }

}
